package com.yun.zf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.common.admin.domain.SysUser;
import com.yun.zf.common.app.domain.SysUserAuth;
import com.yun.zf.common.enums.TopicEnum;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.mapper.SysUserMapper;
import com.yun.zf.system.mq.RocketMqHelper;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.ISysUserService;
import com.yun.zf.system.service.SysUserAuthService;
import com.yun.zf.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService
{

    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysUserAuthService userAuthService;

    @Autowired
    private RocketMqHelper rocketMqHelper;

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName ,Long userId )
    {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserName,userName).eq(SysUser::getUserId,userId);
       SysUser user = baseMapper.selectOne(queryWrapper);
        return user;
    }


    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows =  baseMapper.insert(user);
       // int rows = userMapper.insertUser(user);
        //新增用户id 与手机号码索引表
        // 新增用户与角色管理 注册默认为普通用户
        userRoleService.addUserRole(user);
        return rows;
    }

    @Override
    @Transactional
    public Long addLoginUser(SysUserAuth userAuth,String inviteId) {
        SysUser user = new SysUser();
        // 第三方账户登录默认密码为123456
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode("123456"));
        // 这里不创建用户，在解析手机号码之后对数据进行更新
        //user.setUserName(String.valueOf(userAuth.getIphone()));
        int userCount  = this.insertUser(user);
        // 保存手机号码，登录用户关系表做分库使用
        userAuth.setUserId(user.getUserId());
       Boolean authCount =  userAuthService.save(userAuth);

        Map<String,String> map = new HashMap<>();
        map.put("inviteId",inviteId);
        map.put("invitedId",String.valueOf(user.getUserId()));

       // 发送消息进入MQ
        rocketMqHelper.asyncSend(TopicEnum.INVITE.getInfo(), MessageBuilder.withPayload(map).build());

       if (userCount>0&&authCount){
           return  user.getUserId();
       }
       throw  new CustomException("用户注册失败");
    }

    @Override
    public SysUser getUserById(Long userId) {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(SysUser::getUserId,userId);
        return  baseMapper.selectOne(userQueryWrapper);
    }

    @Override
    public int getUserCountById(Long userId) {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(SysUser::getUserId,userId);
        return  baseMapper.selectCount(userQueryWrapper);
    }

    @Override
    public void updateUserNameByUserId(Long userId,String userName) {

        baseMapper.updateUserNameByUserId(userId,userName);
    }

    @Override
    public void editPassword(String old, String newPass) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
         baseMapper.editPass(SecurityUtils.getLoginUser().getUserId(),encoder.encode(newPass));
    }
}
